package com.solairen.myapplication.net

import kotlinx.coroutines.Deferred
import retrofit2.Response

/**
 *
 * @Date 2024/2/27 22:32
 */
abstract class BaseRepository {

    protected open suspend fun <T> safeRequest(request: () -> Deferred<Response<T>>): HttpResult<T> {
        return try {
            val result = request().await()
            if (result.isSuccessful) {
                val body = result.body()
                body?.let {
                    if (it is BaseModel<*>) {
                        if (it.code == 0) {
                            HttpResult.Success(it)
                        } else {
                            HttpResult.Failure("model中code不为0")
                        }
                    }
                    HttpResult.Success(it)
                } ?: kotlin.run {
                    HttpResult.Failure("data数据为null")
                }
            } else {
                HttpResult.Failure("${result.code()}: ${result.message()}")
            }
        } catch (e: Exception) {
            HttpResult.Error(e)
        }
    }
}